package cn.huijielong.common.utils;

import cn.huijielong.common.exception.VSException;
import cn.huijielong.modules.sys.entity.SysUserEntity;

import java.util.Date;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.util.StringUtils;

/**
 * Shiro工具类
 * 
 * @date 2016年11月12日 上午9:49:19
 */
public class ShiroUtils {
	
	private static Map<String, Session> mySessions=new ConcurrentHashMap<>();
	private static long hour=1000* 60 * 60;
	private static Timer sessionTimer=new Timer();
	public static void runSession() {
		sessionTimer.schedule(new TimerTask() {
			@Override
			public void run() {
				clearSession();
				
			}}, 1000*60, hour);
	}
	public static Session getSession() {
		//前端使用了自定义sessionid，后台对应使用session存储
		String mysessionid=HttpContextUtils.getHttpServletRequest().getHeader("mysessionid");
		if(!StringUtils.isEmpty(mysessionid)) {
			Session session=mySessions.get(mysessionid);
			if(session==null) {
				session=SecurityUtils.getSubject().getSession();
				mySessions.put(mysessionid, session);
			}
			return session;
		}
		return SecurityUtils.getSubject().getSession();
	}
	public static void clearSession() {
		String[] keys=mySessions.keySet().toArray(new String[] {});
		
		for(String k:keys) {
			Long time=Long.parseLong(k);
			Long curTime=new Date().getTime();
			long hours = (curTime-time)/hour;
			if(hours>2) {
				mySessions.remove(k);
			}
		}
	}

	public static Subject getSubject() {
		return SecurityUtils.getSubject();
	}

	public static SysUserEntity getUserEntity() {
		return (SysUserEntity)SecurityUtils.getSubject().getPrincipal();
	}

	public static Long getUserId() {
		return getUserEntity().getUserId();
	}
	
	public static void setSessionAttribute(Object key, Object value) {
		getSession().setAttribute(key, value);
	}

	public static Object getSessionAttribute(Object key) {
		return getSession().getAttribute(key);
	}

	public static boolean isLogin() {
		return SecurityUtils.getSubject().getPrincipal() != null;
	}

	public static String getKaptcha(String key) {
		Object kaptcha = getSessionAttribute(key);
		if(kaptcha == null){
			throw new VSException("验证码已失效");
		}
		getSession().removeAttribute(key);
		return kaptcha.toString();
	}

}
